package user

import (
	"gitee.com/aldrice/monitor/ent/object"
	"gitee.com/aldrice/monitor/ent/user"
	"gitee.com/aldrice/monitor/internal/router"
	"strconv"
)

func GetSelfInfo(c *router.Context) error {
	u, err := c.DB().User.Query().
		Where(user.IDEQ(c.UID())).
		Select(user.FieldID, user.FieldUsername, user.FieldEmail).
		First(c.Ctx())
	if err != nil {
		return err
	}
	return c.ApiSuccess(u)
}

// GetUsers
// @Summary Get Users
// @Description 获取用户信息
// @ID get-users
// @Tags object
// @Accept params
// @Produce json
// @Route /users [get]
func GetUsers(c *router.Context) error {
	db, ctx := c.DB(), c.Ctx()
	uQry := db.User.Query()
	if c.QueryParam("object_id") != "" {
		oid, err := strconv.Atoi(c.QueryParam("object_id"))
		if err != nil {
			return err
		}
		_, err = db.User.Query().Where(user.IDEQ(c.UID()), user.HasHaveObjectWith(object.IDEQ(oid))).First(ctx)
		if err != nil {
			return err
		}

		uQry.Where(user.HasHaveObjectWith(object.IDEQ(oid)))
	}

	cnt, err := uQry.Clone().Count(ctx)
	if err != nil {
		return err
	}
	if cnt == 0 {
		return c.StdTable(0, nil)
	}

	offset, limit := c.DeterminePage()
	ord := c.DetermineOrder(user.Columns)
	item, err := uQry.Order(ord).Offset(offset).Limit(limit).All(ctx)
	if err != nil {
		return err
	}
	return c.StdTable(cnt, item)
}
